<template>
  <div>
    <!-- 功能区域 -->
    <div class="model-opt-btn">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button type="primary">导入</el-button>
      <el-button type="primary">导出</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="model-search">
      <el-input v-model="search" placeholder="请输入内容" clearable @clear="load">
        <template #append>
          <el-button icon="el-icon-search" @click="load">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- <el-button class="model-search-btn" @click="load" type="primary">搜索</el-button> -->

    <!-- 表格 -->
    <div>
      <el-table :data="tableData" :locale="locale" border stripe class="model-tables">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="ID" sortable> </el-table-column>
        <el-table-column prop="username" label="用户名" sortable> </el-table-column>
        <el-table-column prop="password" label="密码" sortable> </el-table-column>
        <el-table-column prop="address" label="地址" sortable> </el-table-column>
        <el-table-column prop="age" label="年龄" sortable> </el-table-column>
        <el-table-column prop="sex" label="性别" sortable> </el-table-column>
        <el-table-column prop="phone" label="手机号" sortable></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="handleClick(scope.row)" size="mini">编辑</el-button>
            <el-popconfirm title="确定删除吗？" confirmButtonText="确定" cancelButtonText="取消" icon="el-icon-info" iconColor="red" @confirm="confirmEvent(scope.row.id)">
              <template #reference>
                <el-button type="danger" size="mini">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 新增用户表单 -->
    <el-dialog width="500px" title="新增用户" v-model="addDialog">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="90px">
        <el-form-item label="用户名" prop="username">
          <el-input class="forminputs" v-model="ruleForm.username" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input class="forminputs" v-model="ruleForm.password" autocomplete="off" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input class="forminputs" v-model.number="ruleForm.age" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="ruleForm.sex" label="男"></el-radio>
          <el-radio v-model="ruleForm.sex" label="女"></el-radio>
          <el-radio v-model="ruleForm.sex" label="其他"></el-radio>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input class="forminputs" v-model="ruleForm.phone" autocomplete="off" clearable></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input type="textarea" class="forminputs" v-model="ruleForm.address" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="save('ruleForm')">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import request from "../utils/request.js"; // axios请求工具类

import zhCn from "element-plus/lib/locale/lang/zh-cn";
export default {
  setup() {
    return {
      locale: zhCn,
    };
  },
  data() {
    return {
      addDialog: false, // 新增用户弹窗
      search: "", // 搜索字符
      pageNum: 1, // 当前页码
      pageSize: 10, //每页多少条
      total: 0, //总条数
      tableData: [], // 表格对象
      ruleForm: {
        // 表单对象
        username: "",
        password: "",
        age: 0,
        sex: "男",
        phone: "",
        address: "",
      },
      rules: {
        // 表单校验规则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        age: [
          { required: true, message: "年龄不能为空" },
          { type: "number", message: "年龄必须为数字值" },
          // { required: true, message: "请输入年龄", trigger: "blur" },
          // {
          //   min: 1,
          //   max: 3,
          //   message: "长度在 1 到 3 个字符",
          //   trigger: "blur",
          // },
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "blur" },
          {
            min: 1,
            max: 3,
            message: "长度在 1 到 3 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            min: 1,
            max: 3,
            message: "长度在 1 到 3 个字符",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" },
          {
            min: 1,
            max: 3,
            message: "长度在 1 到 3 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    // console.log("页面初始化完成！");
    this.load();
  },
  activated() {
    // 实时更新表格数据
    // console.log("加载数据！");
    this.load();
  },
  methods: {
    // 加载数据
    load() {
      this.tableData = [];
      request
        .get("/api/user/pageUser", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.pageSize = res.data.size;
          this.pageNum = res.data.current;
        });
    },

    // 保存用户
    save(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          console.log("校验成功");
          request.post("/api/user/saveUser", this.ruleForm).then(
            (res) => {
              // 加载数据
              this.load();
              this.$message.success({
                message: res.msg,
                showClose: true,
              });
            },
            (error) => {
              this.$message.error({
                showClose: true,
                message: "更新用户失败</br>" + error,
                dangerouslyUseHTMLString: true,
              });
            }
          );
          this.$data.addDialog = false;
          this.ruleForm = {};
          console.log("提交数据完成");
        } else {
          console.log("校验失败");
          return false;
        }
      });
    },
    // 删除用户
    delUser(e) {
      var url = "/api/user/delUser/";
      request.delete(url + e).then(
        (res) => {
          // 加载数据
          this.load();
          this.$message.success({
            message: res.msg,
            showClose: true,
          });
        },
        (error) => {
          this.$message.error({
            showClose: true,
            message: "删除用户失败</br>" + error,
            dangerouslyUseHTMLString: true,
          });
        }
      );
    },

    // 新增弹窗
    add(ruleForm) {
      this.$data.addDialog = true;
      this.ruleForm = {};
      this.ruleForm.sex = "男";
      // this.load();
    },
    // 关闭新增
    closeForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
      this.addDialog = false;
      // this.load();
    },
    // 编辑表格按钮
    handleClick(e) {
      this.ruleForm = JSON.parse(JSON.stringify(e));
      this.$data.addDialog = true;
    },

    //每页最多显示条数10   20   30   50
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.load();
    },
    //翻页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.load();
    },
    // 删除用户
    confirmEvent(e) {
      console.log("删除用户：" + e);
      this.delUser(e);
    },
  },
};
</script>
<style scoped>
/* 表格 */
.model-table {
  width: 100%;
  padding: 10px;
}

/* 功能区域按钮 */
.model-opt-btn {
  margin: 5px 0;
}

/* 搜索区域 */
.model-search {
  margin: 5px 0;
  width: 30%;
}

/* 搜索按钮 */
.model-search-btn {
  margin-left: 5px;
}

/* 新增用户表单 */
.forminputs {
  width: 85%;
}

/* 分页 */
.model-pages {
  margin: 10px 0;
}
</style>